package top.gdonly.signin.sevelets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.json.JSONException;
import org.json.JSONObject;

import top.gdonly.signin.mapper.UserMapper;
import top.gdonly.signin.po.User;
import utils.SqlSessionFactoryUtil;

/**
 * Servlet implementation class LoginSevelet
 */
@WebServlet("/LoginSevelet")
public class LoginSevelet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginSevelet() {
        super();
        // TODO Auto-generated constructor stub
    }


    /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("user_id");
		String pwd = request.getParameter("pwd");
		System.err.println(id + pwd);
		SqlSession session = SqlSessionFactoryUtil.openSession();
		UserMapper userMapper = session.getMapper(UserMapper.class);
		User user =  userMapper.findById(id);
		if(pwd.equals(user.getPwd())){
			JSONObject object=new JSONObject();
			try {
				object.put("state", true);
				object.put("id", user.getId());
				object.put("class_id", user.getClassId());
				object.put("name", user.getName());
				object.put("position", user.getPosition());
				object.put("ssid", user.getSsid());
				object.put("mac", user.getMac());
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(object.toString());
				System.err.println(object.toString());
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		else{
			JSONObject object=new JSONObject();
			try {
				object.put("state", false);
				response.getWriter().write(object.toString());
				System.err.println(object.toString());
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		//doGet(request, response);
	}

}
